<template>
  <div class="relative w-full h-screen">
    <!-- 地图容器 -->
    <div id="map" class="absolute inset-0 w-full h-full"></div>

    <!-- 控制面板 -->
    <div class="absolute inset-x-0 top-0 p-4 bg-white bg-opacity-80">
      <h1 class="text-3xl font-bold mb-4 text-center">城市间路线规划</h1>
      <div class="flex justify-center mb-4">
        <input
            v-model="originCity"
            placeholder="输入起始城市"
            class="border-2 border-gray-300 rounded-lg p-2 w-1/4 mr-2 focus:outline-none focus:border-blue-500 transition duration-200"
        />
        <input
            v-model="destinationCity"
            placeholder="输入目标城市"
            class="border-2 border-gray-300 rounded-lg p-2 w-1/4 mr-2 focus:outline-none focus:border-blue-500 transition duration-200"
        />
        <button
            @click="fetchRoute"
            class="bg-blue-500 text-white font-semibold rounded-lg p-2 hover:bg-blue-600 transition duration-200"
        >
          获取路线
        </button>
      </div>
    </div>

    <!-- 城市列表 -->
    <div class="absolute right-0 top-24 p-4 bg-white bg-opacity-80 rounded-l-lg max-w-xs overflow-y-auto max-h-[calc(100vh-6rem)]">
      <h2 class="text-xl font-semibold mb-2">经过的城市</h2>
      <ul class="list-disc pl-5">
        <li
            v-for="(stop, index) in stops"
            :key="index"
            class="text-gray-800"
        >
          {{ stop }}
        </li>
      </ul>
    </div>
  </div>
</template>
<style scoped>
#map {
  width: 100%;
  height: 100%;
}

/* 添加一些响应式样式 */
@media (max-width: 640px) {
  .absolute.inset-x-0.top-0 {
    position: static;
    background: white;
  }

  .absolute.right-0.top-24 {
    position: static;
    margin-top: 1rem;
    max-width: none;
  }
}
</style>
<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import {key_web_js} from '@/mapConfig'
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
  name: 'CityRoutePlanner2',
  setup() {
    const originCity = ref('南京'); // 默认起始城市
    const destinationCity = ref('北京'); // 默认目标城市
    const stops = ref([]); // 经由的城市
    const map = ref(null); // 地图实例

    const fetchRoute = async () => {
      try {
        const response = await axios.get(`http://localhost:8081/api/route-cities2?origin=${originCity.value}&destination=${destinationCity.value}`);
        const cities = response.data;
        console.log('Received cities data:', cities);
        stops.value = Object.keys(cities);

        drawRouteOnMap(cities);
      } catch (error) {
        console.error('获取路线失败:', error);
      }
    };

    const drawRouteOnMap = async (cities) => {
      try {
        const AMap = await AMapLoader.load({
          key: key_web_js,
          version: '1.4.15',
          plugins: ['AMap.Polyline', 'AMap.Marker'],
        });

        const waypoints = Object.keys(cities).map(city => {
          const location = cities[city].split(',');
          console.log(`City: ${city}, Location: ${location}`);
          if (location.length !== 2 || isNaN(Number(location[0])) || isNaN(Number(location[1]))) {
            console.error(`Invalid coordinates for city ${city}: ${cities[city]}`);
            return null;
          }
          return new AMap.LngLat(Number(location[0]), Number(location[1]));
        }).filter(point => point !== null);

        console.log('Waypoints:', waypoints);

        if (waypoints.length < 2) {
          console.error('Not enough valid waypoints to draw a route');
          return;
        }

        if (!map.value) {
          map.value = new AMap.Map('map', {
            zoom: 6,
            center: waypoints[0],
          });
        }

        const polyline = new AMap.Polyline({
          path: waypoints,
          borderWeight: 4,
          strokeColor: '#FF33FF',
          strokeOpacity: 0.8,
        });

        map.value.remove(polyline);
        polyline.setMap(map.value);

        waypoints.forEach((point, index) => {
          new AMap.Marker({
            position: point,
            title: Object.keys(cities)[index],
            map: map.value,
          });
        });

        // 在添加所有标记后，调整地图视图
        map.value.setFitView(null, false, [60, 60, 60, 60]);

      } catch (error) {
        console.error('绘制路线失败:', error);
      }
    };

    onMounted(() => {
      // 可以在加载时预先绘制一个默认地图
      initDefaultMap();
    });

    const initDefaultMap = () => {
      AMapLoader.load({
        key: '538ad44097e0b56a7e4c4ef7dce5a3c8',
        version: '1.4.15',
        plugins: [],
      }).then((AMap) => {
        map.value = new AMap.Map('map', {
          zoom: 4, // 调整初始缩放级别以显示更大范围
          center: [116.397428, 39.90923], // 默认中心点
          resizeEnable: true, // 启用自动调整大小
        });
      }).catch(error => console.error('初始化地图失败:', error));
    };

    return {
      originCity,
      destinationCity,
      fetchRoute,
      stops,
    };
  },
};
</script>

<style scoped>
.container {
  max-width: 800px;
}
#map {
  width: 100%;
  height: 400px;
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>